/**
 * 本代码实现了节点的管理
 * 1.添加
 * 2.修改
 * 3.删除
 */
package com.bf.zk.node;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import com.bf.tool.DoCue;
import com.bf.zk.constants.Constants;
import com.bf.zk.table.CheckHeaderCellRenderer;
import com.bf.zk.table.CheckTableModle;
import com.bf.zk.table.UserMouseAdapter;
import com.bf.zk.table.UserTable;

/**
 * 刻录机节点管理界面
 * @author Administrator
 *
 */
public class NodeManage extends JFrame implements ActionListener,MouseListener {

	private static final long serialVersionUID = 1L;
	private JFrame nodeManagerWin;
	@SuppressWarnings("unused")
	private JTable mytable;
	private JFrame parent;
	private JPanel contentPane;
	private JTable table;
	private Vector<String> headerNames;
	private DoCue dCue;
	private ArrayList<Node> nodedata=null;
	public NodeManage(JFrame parent, boolean modal) {
		this.parent = parent;
		// 显示设置
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);
		nodeManagerWin = new JFrame("节点管理");
		nodeManagerWin.setSize(800, 600);
		nodeManagerWin.setDefaultCloseOperation(3);
		nodeManagerWin.setResizable(false);
		// 居中显示
		GetNodeData();
		nodeManagerWin.setLayout(null);
		nodeManagerWin.setLocationRelativeTo(parent);
		nodeManagerWin.setIconImage(Toolkit.getDefaultToolkit().createImage("./pic/Log.jpg"));
		nodeManagerWin.getContentPane().setBackground(Constants.mycColor);
		// 用户列表
		nodeTable();
		// 刷新列表
		RefreshNodeList();
		// 按钮布局
		// 增加
		JButton nodeAdd = new JButton("增加节点");
		nodeAdd.setActionCommand("nodeAdd");
		nodeAdd.setBounds(120, 485, 150, 60);

		// 修改
		JButton nodeModify = new JButton("修改节点");
		nodeModify.setActionCommand("nodeModify");
		//nodeModify.setBounds(250, 485, 110, 40);
		nodeModify.setBounds(100, 485, 200, 60);
		nodeModify.setFont(new Font("微软雅黑", Font.BOLD, 30));
		// 删除
		JButton nodeDel = new JButton("删除节点");
		nodeDel.setActionCommand("nodeDel");
		nodeDel.setBounds(380, 485, 110, 40);

		// 返回
		JButton nodeBack = new JButton("返回");
		nodeBack.setActionCommand("nodeBack");
		nodeBack.setBounds(490, 485, 200, 60);
		nodeBack.setFont(new Font("微软雅黑", Font.BOLD, 30));

		nodeManagerWin.add(contentPane);
		//nodeManagerWin.add(nodeAdd);
		nodeManagerWin.add(nodeModify);
		//nodeManagerWin.add(nodeDel);
		nodeManagerWin.add(nodeBack);

		nodeBack.addActionListener(this);
		nodeAdd.addActionListener(this);
		nodeModify.addActionListener(this);
		nodeDel.addActionListener(this);
		table.getTableHeader().addMouseListener(this);
		nodeManagerWin.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// 节点增加
		if (e.getActionCommand().equals("nodeAdd")) {
			new NodeAdd(nodeManagerWin,rootPaneCheckingEnabled);
			if (Constants.nodeOrNot&&!Constants.nodeOrNotCan) {
				nodedata.add(Constants.addNode);
				RefreshNodeList();
				dCue=new DoCue();//倒计时提示
				dCue.DoCue(nodeManagerWin,"添加成功!", 3);
			} else if(Constants.nodeOrNotCan){
				dCue=new DoCue();//倒计时提示
				dCue.DoCue(nodeManagerWin,"放弃操作!", 3);
			}else if(!Constants.nodeOrNot&&!Constants.nodeOrNotCan){
				dCue=new DoCue();//倒计时提示
				dCue.DoCue(nodeManagerWin,"放弃操作!", 3);
			}else if(!Constants.nodeOrNot&&Constants.nodeOrNotCan){
				dCue=new DoCue();//倒计时提示
				dCue.DoCue(nodeManagerWin,"添加失败!", 3);
			}
			Constants.nodeOrNot=false;
			Constants.nodeOrNotCan=false;
		}

		// 节点修改
		if (e.getActionCommand().equals("nodeModify")) {int count = 0;
			for (int rowindex = 0; rowindex < table.getRowCount(); rowindex++) {
				if ((boolean) table.getValueAt(rowindex, 0)) {
					count++;
					Constants.Modify = table.getValueAt(rowindex, 1).toString().trim();
					Constants.Modify0 = table.getValueAt(rowindex, 2).toString().trim();
					Constants.Modify1 = table.getValueAt(rowindex, 3).toString().trim();
				}
			}
			if (count == 1) {
				new NodeModify(nodeManagerWin, rootPaneCheckingEnabled);
				if (Constants.nodeOrNot&&!Constants.nodeOrNotCan) {
					String olenodename;
					for (int i = 0; i < nodedata.size(); i++) {
						olenodename=nodedata.get(i).getName();
						if(Constants.Modify0.equals(olenodename)){
							nodedata.get(i).setIPAdd(Constants.addNode.getIPAdd());
							break;
						}
					}
					RefreshNodeList();
					Constants.Modify0 = "";
					Constants.Modify1 = "";
					Constants.Modify2 = "";
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(nodeManagerWin,"修改成功!", 3);
				} else if(Constants.nodeOrNotCan){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(nodeManagerWin,"放弃操作!", 3);
				}else if(!Constants.nodeOrNot&&!Constants.nodeOrNotCan){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(nodeManagerWin,"放弃操作!", 3);
				}else if(!Constants.nodeOrNot&&Constants.nodeOrNotCan){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(nodeManagerWin,"添加失败!", 3);
				}
				Constants.nodeOrNot=false;
				Constants.nodeOrNotCan=false;
			} else {
				JOptionPane.showMessageDialog(nodeManagerWin, "选择一个操作目标!", "警告",JOptionPane.WARNING_MESSAGE);
			}
		}

		// 节点删除
		if (e.getActionCommand().equals("nodeDel")) {
			boolean flag = false;
			int addDelCount=0;
			for (int rowindex = 0; rowindex < table.getRowCount(); rowindex++) {
				if ((boolean) table.getValueAt(rowindex, 0)	) {
					flag = true;
					addDelCount++;
				}
			}
			if (flag) {
				int delCount=0;
				int cont = JOptionPane.showConfirmDialog(nodeManagerWin, "是否删除，数据将无法恢复?",
						"提示", JOptionPane.OK_OPTION);
				if (cont == JOptionPane.OK_OPTION) {
					try {
						String fileName = "./sqlite/znzk.db";
						Class.forName("org.sqlite.JDBC");
						Connection conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
						Statement stmt = conn.createStatement();
						for (int rowindex = 0; rowindex < table.getRowCount(); rowindex++) {
							if ((boolean) table.getValueAt(rowindex, 0)) {
								boolean rs = stmt.execute("DELETE FROM znzk_node where nodename='"	+ (String) table.getValueAt(rowindex, 2) + "'");
								delCount++;
								//db.closed();
								for (int i = 0; i < nodedata.size(); i++) {
									if((nodedata.get(i).getIPAdd().trim()).equals((String) table.getValueAt(rowindex, 3))){
										nodedata.remove(i);
										break;
									}
								}
							}
						}
					} catch (Exception e2) {
					}
					if (addDelCount==delCount) {
						RefreshNodeList();
						dCue=new DoCue();//倒计时提示
						dCue.DoCue(nodeManagerWin,"删除成功!", 3);
					}else {
						dCue=new DoCue();//倒计时提示
						dCue.DoCue(nodeManagerWin,"删除失败!", 3);
					}
				}else if(cont == JOptionPane.NO_OPTION){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(nodeManagerWin,"放弃操作!", 3);
					RefreshNodeList();
				}else if(cont == JOptionPane.CANCEL_OPTION){
					dCue=new DoCue();//倒计时提示
					dCue.DoCue(nodeManagerWin,"放弃操作!", 3);
					RefreshNodeList();
				}else {
					RefreshNodeList();
				}
				
			} else {
				JOptionPane.showMessageDialog(nodeManagerWin, "选择一个操作目标!", "警告",
						JOptionPane.WARNING_MESSAGE);
			}
		}

		// 返回
		if (e.getActionCommand().equals("nodeBack")) {
			parent.setVisible(true);
			nodeManagerWin.setVisible(false);
		}
	}
	
	public final void RefreshNodeList() {
		initNodeTable();
		table.getColumnModel().getColumn(0).setMinWidth(80);
		table.getColumnModel().getColumn(0).setMaxWidth(80);
		table.getColumnModel().getColumn(1).setMinWidth(0);
		table.getColumnModel().getColumn(1).setMaxWidth(0);
		table.getColumnModel().getColumn(2).setMinWidth(250);
		table.getColumnModel().getColumn(2).setMaxWidth(250);
		table.getColumnModel().getColumn(3).setMinWidth(252);
		table.getColumnModel().getColumn(3).setMaxWidth(252);
	}

	private void nodeTable() {
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		table = new UserTable();
		table.addMouseListener(new UserMouseAdapter() {
	     	   @SuppressWarnings("static-access")
			public void mouseSingleClicked(final MouseEvent e){
	     		  if (e.getButton() == e.BUTTON1) {
	     			  int rowI  = table.rowAtPoint(e.getPoint());// 得到table的行号
	     			  int col=table.columnAtPoint(e.getPoint());
	     			  if (0<col) {
	     				  if ((boolean) table.getValueAt(rowI, 0)) {
	     					  table.setValueAt(false, rowI, 0);
	     				  } else {
	     					  table.setValueAt(true, rowI, 0);
	     				  }
	     			  }
	  			}
	     	  }
	     	   @SuppressWarnings("unused")
			public void mouseDoubleClicked(MouseEvent e){
		     	      int rowI  = table.rowAtPoint(e.getPoint());// 得到table的行号
		     	     int col=table.columnAtPoint(e.getPoint());
		     	     if (rowI > -1){
		     	         //System.out.println("双击鼠标 "+(table.getModel()).getValueAt(rowI, 1));
		     	     }
		     	    
	     	    }
	     	  });
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
		tcr.setHorizontalAlignment(JLabel.CENTER);
		table.setDefaultRenderer(Object.class, tcr);
		table.getTableHeader().setReorderingAllowed(false); 
		table.setRowHeight(40);// 设置行高
		table.setFont(new Font("", Font.PLAIN, 30));
		JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		contentPane.add(scrollPane);
		contentPane.setBounds(80, 15, 600, 447);
		headerNames = new Vector<String>();
		headerNames.add("全选");
		headerNames.add("ID");
		headerNames.add("节点名称");
		headerNames.add("节点地址");
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void initNodeTable() {
		int rowCount = ((DefaultTableModel) table.getModel()).getRowCount();
		// 删除表里之前内容
		for (int i = rowCount - 1; i >= 0; i--) {
			((DefaultTableModel) table.getModel()).removeRow(i);
		}
		Vector<Vector<Comparable>> data = this.getData();
		CheckTableModle tableModel = new CheckTableModle(data, headerNames);
		table.setModel(tableModel);
//        RowSorter sorter = new TableRowSorter(tableModel); 
//        table.setRowSorter(sorter); 
		table.getTableHeader().setDefaultRenderer(new CheckHeaderCellRenderer(table));
	}

	// 获得数据
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Vector getData() {
		Vector data = new Vector();
		for (int i = 0; i < nodedata.size(); i++) {
			Vector rowVector1 = new Vector();
			rowVector1.add(nodedata.get(i).isChooseNode());
			rowVector1.add(nodedata.get(i).getNodeId());
			rowVector1.add(nodedata.get(i).getName());
			rowVector1.add(nodedata.get(i).getIPAdd());
			data.add(rowVector1);
		}
		return data;
	}
	private void GetNodeData(){
		nodedata=new ArrayList<Node>();
		String fileName = "./sqlite/znzk.db";
		try {
			Class.forName("org.sqlite.JDBC");
			Connection conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
			Statement stmt = conn.createStatement();
			java.sql.ResultSet rs = stmt.executeQuery("SELECT * FROM znzk_node");
			while (rs.next()) {
				Node rowNode = new Node();
				rowNode.setChooseNode(false);
				rowNode.setNodeId(rs.getString("nodeid"));
				rowNode.setName(rs.getString("nodename"));
				rowNode.setIPAdd(rs.getString("nodeip"));
				nodedata.add(rowNode);
			}
			conn.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
	//添加响应排序
		@SuppressWarnings("static-access")
		public void mouseClicked(MouseEvent e) {}
		public void mousePressed(MouseEvent e) {}
		public void mouseReleased(MouseEvent e) {}
		public void mouseEntered(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}
}
